﻿using System;
using System.IO;
using System.ServiceModel.Channels;
using System.Xml;

namespace suanpan.API.Components.Core
{
    public static class HttpStreamReader
    {
        public static string ReadRawEntityBody(Message message)
        {
            string result = string.Empty;
            Stream stream = new MemoryStream();
            XmlWriter writer = XmlWriter.Create(stream);
            XmlDictionaryWriter xmlDW =
               XmlDictionaryWriter.CreateDictionaryWriter(writer);
            try
            {
                message.WriteBodyContents(xmlDW);
                xmlDW.Close();
                XmlDocument doc = new XmlDocument();
                result = ReadContentsFromStream(stream, true);
                doc.LoadXml(result);
                stream = new MemoryStream(Convert.FromBase64String(doc.SelectSingleNode("Binary").InnerText));
                result = ReadContentsFromStream(stream, true);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            return result;
        }

        public static string ReadContentsFromStream(Stream stream, bool KeepOpen)
        {
            string str;

            try
            {
                if (stream.CanSeek)
                {
                    stream.Position = 0;
                }

                StreamReader streamReader = new StreamReader(stream, true);
                str = streamReader.ReadToEnd();
                streamReader.Close();
            }
            finally
            {
                if (!KeepOpen)
                    stream.Close();
            }

            return str;
        }

    }
}